<template>
  <bg-vue>
    <template #imgFixed>
      <img src="@/assets/imgV2/exchange-bg-bottom.jpg" />
    </template>
    <template #img>
      <img src="@/assets/imgV2/recharge-bg.png" />
    </template>
    <div class="recharge-page">
      <div class="tit">
        {{ t('recharge.CZLX') }}
      </div>
      <div class="tabs">
        <!-- <button
          @click="tabCoin('PLAY')"
          :class="{ active: coin === 'PLAY' }"
          class="l"
          >PLAY</button
        > -->
        <button
          @click="tabCoin('PT')"
          :class="{ active: coin === 'PT' }"
          class="r"
          >PT</button
        >
      </div>
      <div class="info">
        <div class="name">{{ coin }} {{ t('walletGm.KY') }}</div>
        <div class="value">{{ sum }}</div>
      </div>
      <div class="ipt">
        <van-field
          v-model="valueAt"
          type="number"
          :border="false"
          :placeholder="t('recharge.SRCZ')"
        />
      </div>
      <div class="btns">
        <van-button @click="onRecharge">{{
          t('walletGm.recharge')
        }}</van-button>
        <router-link :to="'/rechargeRecord?coin=' + coin">{{
          t('recharge.Record')
        }}</router-link>
      </div>
    </div>
  </bg-vue>

  <van-overlay :show="show">
    <div class="wrapper" @click.stop>
      <div class="block">
        <van-loading size="24px" color="#fff" vertical>{{
          t('recharge.wait')
        }}</van-loading>
      </div>
    </div>
  </van-overlay>
</template>
<script>
import { balanceOf, getAddress, transfer, watch } from '../dapp'
import {
  GM_ADDRESS,
  RECHARGE_ADDRESS,
  AT_ADDRESS,
  TOKEN_DECIMALS,
} from '../abi'
import http from '../http'
import { state } from '../dapp'
import { Dialog } from 'vant'
import { router } from '@/router'
import BgVue from '@/components/BgVue.vue'

export default {
  data() {
    return {
      show: false,
      valueAt: '',
      coin: 'PT',
      sum: '0',
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const contractAddress = this.coin === 'PT' ? GM_ADDRESS : AT_ADDRESS
      const address = await getAddress()
      const balance = await balanceOf(
        contractAddress,
        address,
        TOKEN_DECIMALS[contractAddress],
      )
      this.sum = balance
    },
    async tabCoin(coin) {
      this.coin = coin
      this.sum = '0'
      this.init()
    },

    async watch(txid) {
      return new Promise((resolve) => {
        var ing = false
        var timer = setInterval(async () => {
          if (!ing) {
            ing = true
            try {
              // var tx = await web3.eth.getTransactionReceipt(txid)
              const res = await http.get(`/api/getTx?txid=${txid}`)
              const tx = res.data
              console.log('tx===', tx)
              if (tx && tx.blockNumber > 0) {
                clearInterval(timer)
                resolve(tx.status)
              }
            } catch (e) {}
            ing = false
          }
        }, 2500)
      })
    },

    async onRecharge() {
      // 未激活询问是否去激活
      if (!state.active) {
        await Dialog.confirm({
          title: this.t('recharge.goActivate'),
          message: this.t('recharge.goActivateHint'),
          confirmButtonText: this.t('common.okText'),
          cancelButtonText: this.t('common.cancelText'),
        }).then(() => {
          router.push('/trade')
        })
        return
      }
      try {
        if (this.valueAt * 1 > 0 && this.valueAt * 1 <= this.sum) {
          // console.log('recharge=', this.valueAt, this.sum)
          const contractAddress = this.coin === 'PT' ? GM_ADDRESS : AT_ADDRESS
          const txid = await transfer(
            contractAddress,
            RECHARGE_ADDRESS,
            this.valueAt,
            TOKEN_DECIMALS[contractAddress],
          )
          this.show = true
          console.log('txid=', txid)
          console.log('wait tx confirm')
          await this.watch(txid)
          console.log('tx was confirm')
          // const res = await http.get(`/api/user/recharge?txid=${txid}`)
          // if (res.data) {
          this.valueAt = '0'
          Toast('充值成功')
          // }
          console.log('reload data')
          this.init()
        }
      } catch (e) {
        Toast(e.message)
        console.log('ee=', e)
      }
      this.show = false
    },
  },
  components: { BgVue },
}
</script>
<style lang="less" scoped>
.recharge-page {
  .tit {
    height: 115px;
    padding: 84px 42px 0 52px;
    color: #ffc53d;
    font-size: 24px;

    text-shadow: 1px 2px 0px rgba(10, 2, 4, 0.2);
    font-weight: bold;
  }
  .tabs {
    display: flex;
    justify-content: space-between;
    padding: 43px 53px 0;

    button {
      width: 123px;
      height: 50px;

      border: none;
      color: #fff;
      font-size: 19px;
      border-radius: 12px;
    }
    button.active {
      background-image: linear-gradient(0deg, #fe7d27 0%, #ffdc43 100%);

      text-shadow: #d8540d 1px 0 2px, #d8540d 0 1px 2px, #d8540d -1px 0 2px,
        #d8540d 0 -1px 2px;
    }
    button + button {
      margin-right: -7px;
    }
  }

  .info {
    display: flex;
    justify-content: space-between;
    height: 44px;

    padding: 24px 52px 0 66px;

    color: #ffffff;
    font-size: 15px;
  }
  .ipt {
    padding: 34px 46px 29px 60px;

    .van-cell {
      padding: 0;
      background: transparent;
    }

    :deep(input) {
      height: 24px;
      padding: 0 8px;
      color: #117fd4;
      font-size: 16px;

      letter-spacing: 1px;

      &::placeholder {
        color: #117fd4;
      }
    }
    // color: #117fd4;
    // font-size: 16px;
    // font-weight: bold;
    // button {
    //   width: 280px;
    //   height: 42px;
    //   text-align: left;
    //   padding-left: 10px;
    // }
  }
  .btns {
    // display: flex;
    // justify-content: space-between;
    // padding: 17px 48px 12px 55px;
    padding: 0 120px 0 130px;
    .van-button,
    a {
      display: block;
      width: 100%;
      height: 42px;

      color: #ffffff;
      font-size: 17px;
      // background-image: linear-gradient(0deg, #fe7d27 0%, #ffdc43 100%),
      //   linear-gradient(#fbba1e, #fbba1e);

      text-shadow: #146092 1px 0 2px, #146092 0 1px 2px, #146092 -1px 0 2px,
        #146092 0 -1px 2px;
      background-color: transparent !important;
      border: none;
      // font-weight: bold;
    }
    .van-button + a {
      display: flex;
      align-items: center;
      justify-content: center;
      text-decoration: underline;

      margin-left: -20px;
      width: 160px;
    }
  }
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
